# Create your views here.

from django.views import View

from model.models import Point
from server.utils import Response, LoginRequiredAdmin, Verify, Code, Request


class PointShareView(LoginRequiredAdmin, View):
    """ User operation points share """

    @Request.getJson
    def post(self, request):
        """ Set an existing point as shared """
        pid = request.JSON.get('pid')

        for code in [Verify.pointPid(pid)]:
            if code != Code.OK:
                return Response.Json(code=code)

        point = Point.objects.get(pid=pid)
        if point.uploader != request.user:
            return Response.Json(code=Code.Error, msg="You don't have permission to set someone else's points")

        if point.type == Point.Type.share:
            return Response.Json(code=Code.Error, msg="This point is already a shared point")

        point.set_type(Point.Type.share)
        point.set_status(Point.Status.apply_approve)
        return Response.Json()

    @Request.getJson
    def put(self, request):
        """ add an shared point """
        name = request.JSON.get('name')
        detail = request.JSON.get('detail')
        longitude = request.JSON.get('longitude')
        latitude = request.JSON.get('latitude')
        direction = request.JSON.get('direction', '')

        for code in [Verify.pointName(name), Verify.pointDetail(detail),
                     Verify.longitude(longitude), Verify.latitude(latitude), Verify.direction(direction)]:
            if code != Code.OK:
                return Response.Json(code=code)

        count = Point.objects.filter(uploader=request.user, type=Point.Type.person).count()
        if count >= 5000:
            return Response.Json(code=Code.Error, msg="Creation failed, personal point limit is 5000")

        point = Point(name=name, detail=detail, longitude=longitude, latitude=latitude, direction=direction,
                      uploader=request.user)
        point.save()

        point.set_type(Point.Type.share)
        point.set_status(Point.Status.apply_approve)
        return Response.Json(point=point.info())
